<template>
  <el-dialog v-bind="$attrs" v-on="$listeners">
    <el-form
      :model="params"
      :rules="teacherRules"
      ref="form"
      label-width="100px"
      size="mini"
    >
      <el-form-item label="教师姓名:" prop="teacher_name">
        <el-input v-model="params.teacher_name"></el-input>
      </el-form-item>
      <el-form-item label="联系电话:" prop="teacher_number">
        <el-input v-model="params.teacher_number"></el-input>
      </el-form-item>
      <el-form-item label="所属院系:" prop="teacher_department_id">
        <el-select clearable v-model="params.teacher_department_id">
          <el-option
            v-for="d in departments"
            :key="d.department_id"
            :label="d.department_name"
            :value="d.department_id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button size="mini" @click="change()">取消</el-button>
      <el-button type="primary" size="mini" @click="confirm()">添加</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { selectDepartmentOptions } from "@/api";
import { insertNewTeacher } from "@/api/teacher";

export default {
  data() {
    return {
      departments: [],
      teacherRules: {
        teacher_department_id: [
          { required: true, message: "请选择所属院系", trigger: "change" },
        ],
        teacher_number: [
          { required: true, message: "请输入教师工号", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        teacher_name: [
          { required: true, message: "请输入教师姓名", trigger: "blur" },
        ],
      },
      params: {
        teacher_department_id: "",
        teacher_number: "",
        teacher_name: "",
      },
    };
  },
  methods: {
    async initDepartmentOptions() {
      let { data } = await selectDepartmentOptions({
        department_name: "",
      });
      this.departments = data;
    },
    change() {
      this.$emit("update:visible", false);
    },
    async confirm() {
      await this.$refs.form.validate();
      await insertNewTeacher(this.params);
      this.$emit("reload");
      this.$emit("update:visible", false);
      this.params = {};
    },
  },
  created() {
    this.initDepartmentOptions();
  },
};
</script>
